package com.mushuilingfeng.ddd.user.infrastructure.repository;

import com.mushuilingfeng.ddd.framework.entity.IDomainEntity;
import com.mushuilingfeng.ddd.framework.repository.IDomainRepository;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 内存存储
 *
 * @author 沐水淋风
 * @date 2024/9/19
 */
@Slf4j
public abstract class BaseMemoryRepository<T> implements IDomainRepository<T> {
    protected final Map<Serializable, Object> db = new HashMap<>();
    
    @SuppressWarnings("unchecked")
    @Override
    public T get(Serializable id) {
        log.info("BaseMemoryRepository get method ,id = {}", id);
        return (T) db.get(id);
    }
    
    @Override
    public void save(T entityOrObjectValue) {
        log.info("BaseMemoryRepository save method");
        saveOrUpdate(entityOrObjectValue);
    }
    
    @Override
    public void update(T entityOrObjectValue) {
        log.info("BaseMemoryRepository update method");
        saveOrUpdate(entityOrObjectValue);
    }
    
    @Override
    public void saveOrUpdate(T entityOrObjectValue) {
        log.info("BaseMemoryRepository saveOrUpdate method");
        if (entityOrObjectValue instanceof IDomainEntity domainEntity) {
            Serializable id = domainEntity.getId();
            if (id != null) {
                db.put(id, entityOrObjectValue);
            }
        }
    }
    
    @Override
    public void delete(Serializable id) {
        log.info("BaseMemoryRepository delete method ,id = {}", id);
        db.remove(id);
    }
    
}
